package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl extends ServiceImpl<BpmnInfoMapper, BpmnInfo> implements IBpmnInfoService {

    @Resource
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    /*
    select id, bpmn_name, bpmn_type, deployment_id, act_process_id, act_process_key,
             deploy_time, info
      from bus_bpmn_info
    <where>
      <if test="beginTime != null">
        and deploy_time &gt;= #{beginTime}
      </if>
      <if test="endTime != null">
        and deploy_time &lt;= #{endTime}
      </if>
    </where>
     */
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        IPage<BpmnInfo> page = new Page<>(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(super.page(page,new LambdaUpdateWrapper<BpmnInfo>()
                .ge(qo.getBeginTime() != null, BpmnInfo::getDeployTime, qo.getBeginTime())
                .le(qo.getEndTime() != null, BpmnInfo::getDeployTime, qo.getEndTime())));
    }


    @Override
    public boolean save(BpmnInfo bpmnInfo) {
        // insert into bus_bpmn_info (bpmn_name, bpmn_type, deployment_id, act_process_id, act_process_key,
        //      deploy_time, info)
        //    values (#{bpmnName}, #{bpmnType}, #{deploymentId}, #{actProcessId}, #{actProcessKey},
        //      #{deployTime}, #{info})
        bpmnInfoMapper.insert(bpmnInfo);
        return true;
    }

    @Override
    public BpmnInfo get(Long id) {
        /*
        select id, bpmn_name, bpmn_type, deployment_id, act_process_id, act_process_key,
            deploy_time, info
            from bus_bpmn_info
            where id = #{id}
         */
        return bpmnInfoMapper.selectById(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        /*
        update bus_bpmn_info
    set bpmn_name = #{bpmnName},
      bpmn_type = #{bpmnType},
      deployment_id = #{deploymentId},
      act_process_id = #{actProcessId},
      act_process_key = #{actProcessKey},
      deploy_time = #{deployTime},
      info = #{info}
    where id = #{id}
         */
        bpmnInfoMapper.updateById(bpmnInfo);
    }

    @Override
    @Transactional
    public void deleteBatch(Long id) {
        BpmnInfo bpmnInfo = this.get(id);
        //查询流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(bpmnInfo.getDeploymentId()).singleResult();
        //删除activiti中流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
        //删除服务器上的文件
        String resourceName = definition.getResourceName();
        File file = new File(SystemConfig.getProfile(), resourceName);
        if (file.exists()) {
            file.delete();
        }
        //删除bpmnInfo对象
        bpmnInfoMapper.deleteById(id);
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectList(null);
    }

    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws IOException {
        File file = new File(SystemConfig.getProfile(), path);
        FileInputStream inputStream = new FileInputStream(file);
        //通过资源管理接口对象，通过获取路径文件和文件进行部署到activiti中
        Deployment deploy = repositoryService.createDeployment().addInputStream(path, inputStream).deploy();
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setInfo(info);
        //通过部署的id查询该id所对应的结果通过对象返回
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        bpmnInfo.setActProcessId(definition.getId());
        bpmnInfo.setBpmnName(definition.getName());
        bpmnInfo.setActProcessKey(definition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
        inputStream.close();
    }

    @Override
    @Transactional
    public InputStream getResourceName(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        if ("xml".equalsIgnoreCase(type)) {
            InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, definition.getResourceName());
            return inputStream;
        } else if ("png".equalsIgnoreCase(type)) {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream inputStream = generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
            return inputStream;
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String carPackage) {
        /*
        select id, bpmn_name, bpmn_type, deployment_id, act_process_id, act_process_key,
           deploy_time, info
    from bus_bpmn_info where bpmn_type = #{carPackage}
         */
        LambdaQueryWrapper<BpmnInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BpmnInfo::getBpmnType,carPackage);
        return bpmnInfoMapper.selectOne(wrapper);
    }
}
